package com.foreveross.bsl.mdm.ios.application.impl;

import com.notnoop.apns.APNS;
import com.notnoop.apns.ApnsNotification;
import com.notnoop.apns.ApnsService;
import com.notnoop.apns.ApnsServiceBuilder;
import com.notnoop.apns.PayloadBuilder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

import java.io.IOException;
import java.io.InputStream;

/**
 * @description 注意Maven 打包会改变证书长度，证书应该当独放置
 *
 * @author heyaowen
 * @version v1.0
 *
 * @2014-7-18
 *
 */
public class ApnsMessageSender implements InitializingBean {
	
	private Log log = LogFactory.getLog(getClass());
	
    private Resource keystore;
    private String password;
    
    public Resource getKeystore() {
        return keystore;
    }

    public void setKeystore(Resource keystore) {
        this.keystore = keystore;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
    /**
     * 唤醒设备，让它去与MDM Server交互指令
     * 
     * @param apnsToken
     * @param pushMagic
     */
    public void wakeUpDevice(String apnsToken, String pushMagic) {
        try {
            InputStream certificate = this.keystore.getInputStream();
            ApnsServiceBuilder serviceBuilder = new ApnsServiceBuilder();
            ApnsService service = serviceBuilder.withProductionDestination()
            		.withCert(certificate, this.password)
            		.build();
            PayloadBuilder payloadBuilder = PayloadBuilder.newPayload().mdm(pushMagic);
            String payload = payloadBuilder.build();
            
            if (log.isDebugEnabled())
                log.debug(String.format("about to send message %s", payload));

            service.push(apnsToken, payload);

        } catch (IOException e) {
            throw new RuntimeException(String.format("couldn't read the key store, '%s'", keystore.toString()), e);
        }
    }
    
    
    /**
     * 另一个唤醒设备方法，让它去与MDM Server交互指令
     * 
     * @param apnsToken
     * @param pushMagic
     * @param pustCerName pushCert.p12
     */
    public void wakeUpDevice(String apnsToken, String pushMagic, String pustCerName) {
    	// jar's classpath
    	// String path = Thread.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    	ApnsService service = APNS.newService()
				.withCert("/app/tomcat6/webapps/mdm/WEB-INF/classes/" + pustCerName, this.password)
				.withProductionDestination().build();
		String mdmPayload = APNS.newPayload().customField("mdm", pushMagic).build();
		ApnsNotification notification =  service.push(apnsToken, mdmPayload);
        
		log.debug(String.format("about to send message %s, token=%s", 
				mdmPayload, notification.getDeviceToken()));
        // if (log.isDebugEnabled()) {}
    }
    
    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(this.password, "the 'password' must not be null");
        Assert.notNull(this.keystore, "the 'key store' must not be null");
    }

}
